import os
import re
import shelve
import time

from selenium import webdriver
from selenium.webdriver import DesiredCapabilities, ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

from settings import TREE, BASE_PATH


class QuixelSelenium:
    def __init__(self) -> None:
        super().__init__()
        self.base_url = "https://quixel.com/megascans/home?"
        self.url_tree = TREE
        self.options = webdriver.EdgeOptions()
        desired_capabilities = DesiredCapabilities.CHROME
        desired_capabilities["pageLoadStrategy"] = "eager"
        self.options.add_experimental_option("detach", True)
        self.browser = webdriver.Edge(options=self.options)
        self.browser.maximize_window()
        self.browser.set_page_load_timeout(30)
        self.wait = WebDriverWait(self.browser, 10)
        self.browser.implicitly_wait(10)
        self.url_list = []
        self.f_shelve = shelve.open('shelve')
        self.downloaded_url_list = self.get_downloaded()
        self.get_url(self.url_tree)
        self.act = ActionChains(self.browser)
        self.cookie = {
            "name": "auth",
            "value": "{%22token%22:%22eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InpoaXdlaTUyMTdAMTI2LmNvbSIsInNjb3BlIjpbImRlZmF1bHQ6dXNlciIsIm1lZ2FzY2Fuczp1c2VyIl0sImVwaWNBY2NvdW50SWQiOiIzNmM1MzgzOTM2ZTU0ZDA3ODRmOGUxMzJlMzgzNDllZCIsImlzVW5yZWFsRVVM"
                     "QUFjY2VwdGVkIjp0cnVlLCJpc0VwaWNBY2NvdW50Ijp0cnVlLCJxdWl4ZWxBY2NvdW50SWQiOiJjNmFlOTI0OC00MGM5LTRlN2MtYTdhZS0yZjNlYjczMGJmZGYiLCJyZWFsbSI6Im1lZ2FzY2FucyIsImV1bGFzQWNjZXB0ZWQiOlsiZXBpY19jb250ZW50IiwidWUiXSwiaWF0IjoxNjcwODEyNDEwLCJleHAiOjE2NzA4NDEyMTA"
                     "sImlzcyI6InF1aXhlbC1zc28tcHJvZCIsImp0aSI6ImFlOTFiMzlkLWZjMmYtNDdhMS1iZDcwLTY3Nzc1NTY5MTAxMyJ9.pq8oGhuh_AkLE35UD2hnP-Rld3Y7J3XfPUjkstv36C2Izb-gqJ_NjZmaNhiWURFT15nVj30pCJT_czx37E--SnGrOzv95KBoDoueBJ_Q8Q7Qirwej0J2eQXCFZLlP1WYgzmnzA2FCjT11KzjiE575LVdw"
                     "Zq5Wj1r4Z_dsDteN5zGbcJpYgswyviZG8_9tsNeYzs55oRF6lDqx83NBtf7abfkMqjZY2NOYRS1-zY-TQExKWM10Z8iXN-iugDkA9Y8pNbHui1m60lPkiZ0MRabtGNo1I0mR_V4fD3f6tnfgX50w0aiIhhRVJoMWhJvaEfipMcSqLsDfi2ff1SCRb3lYw%22%2C%22refreshToken%22:%22MmY4Y2FlMzktZjc1MS00MzA0LTlkMz"
                     "QtYTA3MTE2MThlNWEw%22}",
            "domain": 'quixel.com'
        }
        self.prefs = {'download.prompt_for_download': False, 'download.default_directory': ''}

    def clear(self):
        self.f_shelve.clear()

    def get_downloaded(self):
        arr = []
        try:
            arr = self.f_shelve["url"]
        except Exception as e:
            pass
        return arr

    def get_url(self, tree: dict, base_url=None):
        if not base_url:
            base_url = self.base_url
        for _k, _v in tree.items():
            end_url = base_url + f"&&category={_k}"
            if _v:
                self.get_url(_v, end_url)
            else:
                self.url_list.append(end_url)

    def main(self):
        for i in self.url_list:
            if i in self.downloaded_url_list:
                continue
            else:
                print(self.f_shelve["url"])
                self.downloaded_url_list.append(i)
                self.f_shelve["url"] = self.downloaded_url_list
                res = re.findall("=([^&.]*)", i)
                path = os.path.join(BASE_PATH, *res)
                params = {'behavior': 'allow', 'downloadPath': path}
                self.browser.execute_cdp_cmd('Page.setDownloadBehavior', params)
                self.browser.get(i)
                self.browser.add_cookie(self.cookie)
                time.sleep(5)
                self.browser.refresh()
                time.sleep(10)
                print(f"url:{i}")
                mod_list = self.browser.find_elements(By.CLASS_NAME, "gridDiv___m7dLb")
                count = 0
                for mod in mod_list:
                    count += 1
                    print(f"第{count}个元素")
                    self.act.move_to_element(mod).click(mod).perform()
                    time.sleep(3)
                    download_btn = self.wait.until(
                        EC.presence_of_element_located((By.CLASS_NAME, "Button___1mkoh")))
                    self.act.move_to_element(download_btn).click(download_btn).perform()
                    time.sleep(3)
                    close_button = self.browser.find_element(By.CLASS_NAME, "circle___2RiS2")
                    self.act.move_to_element(close_button).click(close_button).perform()
                    time.sleep(5)

    # def get_cookie(self):
    # self.browser.get("https://quixel.com/megascans/home")
    # login_btn = self.browser.find_element(By.CLASS_NAME, "css-xwv3p2")
    # self.act.move_to_element(login_btn).click(login_btn).perform()
    # ep_but = self.browser.find_element(By.CLASS_NAME, "_3PNMHbJE22xaFXrB596K3i")
    # self.act.move_to_element(ep_but).click(ep_but).perform()
    # # time.sleep(10)
    # ep_login_btn = self.browser.find_element(By.ID, "login-with-epic")
    # self.act.move_to_element(ep_login_btn).click(ep_login_btn).perform()
    # # time.sleep(10)
    # self.browser.find_element(By.ID, "email").send_keys("zhiwei5217@126.com")
    # self.browser.find_element(By.ID, "password").send_keys("zz5217cc")
    # time.sleep(10)
    # login = self.browser.find_element(By.ID, "sign-in")
    # self.act.move_to_element(login).click(login).perform()
    # time.sleep(20)
    # with open("./cookie.txt", "w") as f:
    #     f.write(str(self.browser.get_cookies()))


if __name__ == '__main__':
    a = QuixelSelenium()
    a.clear()
    # a.main()
